package com.alarm.ecp.utils;

import com.alarm.ecp.pojo.DeviceData;
import com.alarm.ecp.pojo.Geometry;
import com.alibaba.fastjson2.JSONObject;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.apache.flink.api.java.utils.ParameterTool;
import org.bson.Document;
import org.locationtech.jts.geom.Coordinate;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import static com.mongodb.client.model.Filters.eq;

public class MatchDemo {
    public static boolean isPointInPolygon(DeviceData data, String[] args) throws IOException {
        // 从命令行参数获取配置文件路径
        ParameterTool parameterTool = ParameterTool.fromArgs(args);

        String configFilePath = parameterTool.get("configPath");
        if (configFilePath == null || configFilePath.isEmpty()) {
            throw new IllegalArgumentException("Missing configPath parameter.");
        }

        // 从指定路径加载 properties 文件
        ParameterTool config = ParameterTool.fromPropertiesFile(new File(configFilePath));

//        MongoClient mongoClient = MongoClients.create(config.get("mongodb.uri"));
//        MongoCollection<Document> collection = mongoClient.getDatabase(config.get("mongodb.database")).getCollection("TAB_CITY_BOUND");
//        String cityId = data.get_area_code().substring(0, 4) + "00";
//        Document administrativeDivision = collection.find(eq("cityId", cityId)).first();
//
//        if (Objects.isNull(administrativeDivision)) {
//            return false;
//        }
//        Document gemometryDoc = administrativeDivision.get("geometry", Document.class);
//        String coordinatesJson = gemometryDoc.toJson();
        String coordinatesJson = "{\"coordinates\": [[[121.0538864, 31.40665054], [121.06480837, 31.40654325], [121.06467962, 31.397295], [121.05380058, 31.397295], [121.0538864, 31.40665054]]], \"type\": \"Polygon\"}";
        Geometry administrativeDivisionGeometry = JSONObject.parseObject(coordinatesJson, Geometry.class);
        Coordinate[] coordinates = GeoFenceUtil.getCoordinates(administrativeDivisionGeometry);
        boolean f = GeoFenceUtil.isPointInPolygon(data.longitude, data.latitude, coordinates);
        return f;
    }
}
